package com.example.maax.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.example.maax.entity.Task;
import com.example.maax.mapper.TaskMapper;
import com.example.maax.vo.TaskQueryDTO;
import com.example.maax.vo.TaskReqVO;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException.NotFound;
import org.springframework.web.server.ResponseStatusException;

import java.time.LocalDateTime;
import java.util.Base64;
import java.util.List;

import static com.example.maax.controller.RemoteController.HEART_BEAT;

@RestController
@RequestMapping("/task")
@RequiredArgsConstructor
public class TaskController {
    private final TaskMapper taskMapper;

    @GetMapping
    public Object list(TaskQueryDTO queryDTO) {
        List<Task> list = ChainWrappers.lambdaQueryChain(taskMapper)
                .select(Task::getId, Task::getType, Task::getStatus, Task::getUpdateTime)
//                .eq(StringUtils.hasText(queryDTO.getUserId()), Task::getUserId, queryDTO.getUserId())
                .eq(StringUtils.hasText(queryDTO.getDeviceId()), Task::getDeviceId, queryDTO.getDeviceId())
                .ne(Task::getType, HEART_BEAT)
                .orderByDesc(List.of(Task::getCreateTime, Task::getId))
                .last("limit 100")
                .list();
        return JSON.toJSONString(list);
    }

    @GetMapping("/{id}")
    public Object get(@PathVariable String id) {
        Task task = ChainWrappers.lambdaQueryChain(taskMapper)
                .eq(Task::getId, id)
                .one();
        return JSON.toJSONString(task);
    }

    @GetMapping(value = "/{id}/snapshot", produces = MediaType.IMAGE_JPEG_VALUE)
    public Object getSnapshot(@PathVariable String id) {
        Task task = ChainWrappers.lambdaQueryChain(taskMapper)
                .select(Task::getPayload)
                .eq(Task::getId, id)
                .one();
        if (task == null) {
            throw NotFound.create(HttpStatusCode.valueOf(404), "not found", null, null, null);
        }
        return Base64.getDecoder().decode(task.getPayload());
    }

    @PostMapping
    public void create(@RequestBody TaskReqVO reqVO) {
        Task task = TaskReqVO.convert(reqVO);
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(task.getCreateTime());
        taskMapper.insert(task);
    }

    @PutMapping("/{id}")
    public void update(@PathVariable String id, @RequestBody TaskReqVO reqVO) {
        if (ChainWrappers.lambdaQueryChain(taskMapper)
                .eq(Task::getId, id)
                .eq(Task::getStatus, 2)
                .exists()) {
            throw new ResponseStatusException(400, "任务已完成", null);
        }

        Task task = TaskReqVO.convert(reqVO);
        task.setId(id);
        task.setUpdateTime(LocalDateTime.now());
        taskMapper.updateById(task);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable String id) {
        taskMapper.deleteById(id);
    }
}
